# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2018/12/7
# python-version    : Python 3.7.0
# description       : 12306 火车 <br>
#                     12306查询地址:https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2018-12-07&leftTicketDTO.from_station=CQW&leftTicketDTO.to_station=BJP&purpose_codes=ADULT
#                     12306城市列表查询地址:https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9077

'''
命令行查询12306火车票

Usage:
    tickets [-gdtkzc] <origin> <destination> <date>

Options:
    -h,--help   显示帮助菜单
    -g          高铁
    -d          动车
    -t          特快
    -k          快速
    -z          直达
    -c          城际

Examples:
    tickets 北京 重庆 2018-12-08
    tickets -dg 重庆 成都 2018-12-08
'''
import prettytable
import requests
from docopt import docopt
from com.python.demo.tickets_qry.stations import stations
from colorama import init, Fore

# 基本参数
invert_stat = dict(zip(stations.values(), stations.keys()))
init()


def cli():
    """Command-line interface"""
    arguments = docopt(__doc__)
    begin_station = stations.get(arguments['<origin>'])
    end_station = stations.get(arguments['<destination>'])
    date = arguments['<date>']
    url = 'https://kyfw.12306.cn/otn/leftTicket/query' \
          '?leftTicketDTO.train_date={}' \
          '&leftTicketDTO.from_station={}' \
          '&leftTicketDTO.to_station={}' \
          '&purpose_codes=ADULT'.format(date, begin_station, end_station)

    # 获取参数
    options = ''.join([
        key for key, value in arguments.items() if value is True
    ])
    response = requests.get(url)
    # print(response.text.encode("utf-8"))
    avariable_trains = response.json()['data']['result']
    # print(response.json())
    trains = TrainsCollection(avariable_trains, options)
    trains.pretty_print()
    # print(response.json()['data'])
    # print(response.json()['data']['result'])


class TrainsCollection:
    header = "车次  车站  时间  历时  商务  一等  二等  软卧  硬卧  硬座  无座 ".split()

    def __init__(self, available_trains, options):
        """查询到的列车班次集合
        :param available_trains:一个列表，包含可获得的列车班次，每个火车班次是一个字典
        :param options:查询的选项，如：高铁，动车，等"""
        self.available_trains = available_trains
        self.options = options


    def _add_tag(self, station1, station2, flag=0):
        if station1 == station2:
            if flag == 0:
                return Fore.RED + '始 ' + Fore.GREEN + invert_stat[station2] + Fore.RESET
            else:
                return Fore.GREEN + '终 ' + Fore.GREEN + invert_stat[station2] + Fore.RESET
        else:
            return Fore.CYAN + '过 ' + Fore.GREEN + invert_stat[station2] + Fore.RESET

    def _get_duration(self, raw_train):
        duration = str(raw_train[10].replace(":", "小时") + "分")
        if duration.startswith('00'):
            return duration[4:]
        if duration.startswith('0'):
            return duration[1:]
        return duration

    @property
    def trains(self):
        for raw_train in self.available_trains:
            # print(raw_train)
            train_list = list(str(raw_train).split('|'))
            train_no = str(train_list[3])
            initial = train_no[0].lower()
            if not self.options or initial in self.options:
                train = [
                    train_no,
                    '\n'.join(
                        [self._add_tag(train_list[4], train_list[6]), self._add_tag(train_list[5], train_list[7], 1)]),
                    '\n'.join([Fore.GREEN + '出发 ' + train_list[8] + Fore.RESET,
                               Fore.BLUE + '到达 ' + train_list[9] + Fore.RESET]),
                    self._get_duration(train_list),
                    train_list[32],
                    train_list[31],
                    train_list[30],
                    train_list[23],
                    train_list[28],
                    train_list[29],
                    train_list[26],

                ]
                yield train

    def pretty_print(self):
        pt = prettytable.PrettyTable()
        pt._set_field_names(self.header)
        for train in self.trains:
            pt.add_row(train)
        print(pt)


if __name__ == '__main__':
    cli()
